import apiConfig, { baseUrl } from "./apiConfig";

export default function ({ name, data: _data = {}, success, fail, complete, config: { method, header = {} } = {} }) {
  let api = apiConfig;
  for (var key of name.split(".")) api = api[key] || console.error(`找不到名为 ${key}的api接口,在api列表${api}中`);
  let { url, query = {}, form = {}, config: { method: _method, _header = {} } = {}, disp="", data:data_} = api;
  //console.debug(`call api ${name}`, api, arguments[0], "require arguments:", form, query);
  console.info(`督诗Api${name}: ${disp}`)
  console.info(`督诗Api需要的参数data有：${Object.keys(form).concat(Object.keys(query))}`)
  if(data_) console.info(`它其中的一些些参数的取值如下\n${Object.keys(data_).map(k=>`${k}: ${JSON.stringify(data_[k])}`).join(",\n")}`);
  if (url) {
    if(name.indexOf(".")==-1)
      var url_="";
    else
      var url_ = name.replace(/\.[^\.]*$|\./g, "/");
    url = url_ + url.replace(/\{(.*)}/, function (match, k) {
      return _data[k] || console.error(`ds: 找不到${k}，在你给的参数data${JSON.stringify(_data)}中`)
    }).replace(/\*/g, key);
  } else
    url = name.replace(/\./g, "/");
  url = baseUrl + url;
  method = method || _method;
  header = { ..._header, ...header };
  var data = {}, param = {};
  if (form._)
    form = { ...form._, ...form[method || "GET"] };
  if (query._)
    query = { ...query._, ...query[method || "GET"] };
  for (var key in form) {
    if (key in _data)
      data[key] = _data[key];
    else {
      let value = form[key];
      if (value||value=="")
        data[key] = value;
      else if (typeof value == "object")
        console.error(`ds: 找不到${key}，在你给的参数data${JSON.stringify(_data)}中`);
    }
  }
  for (var key in query) {
    if (key in _data)
      param[key] = _data[key];
    else {
      let value = query[key];
      if (value||value=="")
        param[key] = value;
      else if (typeof value == "object")
        console.error(`ds: 找不到${key}，在你给的参数data${JSON.stringify(_data)}中`);
    }
  }
  let queryStr = Object.keys(param).map(key => `${key}=${param[key]}`).join("&");
  if (queryStr)
    url = url + "?" + queryStr;
  return new Promise((resolve, reject) => {
    //console.debug("调用wx.request时的参数：", { url, method, data, header});
    wx.request({
      url, method, data, header, complete,
      success: res => {
        if (res.data.status) {
          let e = new Error(res.data.message);
          e.code = res.data.status;
          if (fail) fail(e);
          return reject(e);
        }
        if (success) success(res.data);
        resolve(res.data);
      },
      fail: e => {
        if ("errMsg" in e)
          (e = new Error("(⋟﹏⋞)\n网络连接出错了呢")).code = -1;
        if (!("message" in e))
          (e = new Error("(＞_＜)\n出现了未知错误")).code = -1;
        console.debug(e);
        if (fail) { fail(e); }
        reject(e);
      }
    });
  })
}
